import java.awt.event.ActionEvent;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextField;
import javax.swing.Timer;

public class PillarController implements Runnable 
{
	private static int currentPillar;
	private static int previousPillar;
	private State state;
	private LEDController ledController;
	private Timer timer;
	private JTextField textField;
	
	public PillarController(State state, LEDController ledController, int changeTime, JTextField textField)
	{
		this.state = state;
		this.ledController = ledController;
		timer = new Timer(changeTime*1000, pillarAction());
		this.textField = textField;
	}
	
	public void run()
	{
		startSequence();
		randomPillar();
		lightPillar();
	}
	
	public void lightPillar()
	{
			ledController.LEDOff(previousPillar-1);
			try
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e)
			{}
			ledController.LEDOn(currentPillar-1);
			timer.start();
	}
	
	public void pillarBlink()
	{
		for (int i = 0; i < 2; i++)
		{
			ledController.LEDOff(currentPillar-1);
			try
			{
				Thread.sleep(200);
			}
			catch (InterruptedException e)
			{}
			ledController.LEDOn(currentPillar-1);
			try
			{
				Thread.sleep(200);
			}
			catch (InterruptedException e)
			{}
		}
	}
	
	public Action pillarAction()
	{
		return new AbstractAction()
		{
			public void actionPerformed(ActionEvent e)
			{
				randomPillar();
				lightPillar();
			}
		};
	}
	
	public void pillarHit()
	{
		timer.stop();
		pillarBlink();
		state.setScore(state.getScore()+1);
		textField.setText("Current score: " + Integer.toString(state.getScore()));
		randomPillar();
		lightPillar();
	}
	
	public void randomPillar()
	{
		int i;
		Random rand = new Random();
		i = rand.nextInt(3)+1;
		if (i == currentPillar)
		{
			randomPillar();
		}
		else
		{
			previousPillar = currentPillar;
			currentPillar = i;
			state.setPreviousPillar(previousPillar);
			state.setCurrentPillar(currentPillar);
		}
	}
	
	public void startSequence()
	{
		for (int i = 0; i < 3; i++)
		{
			ledController.LEDOn(0);
			ledController.LEDOn(1);
			ledController.LEDOn(2);
			try
			{
				Thread.sleep(200);
			}
			catch (InterruptedException e)
			{}
			ledController.LEDOff(0);
			ledController.LEDOff(1);
			ledController.LEDOff(2);
			try
			{
				Thread.sleep(200);
			}
			catch (InterruptedException e)
			{}
		}
	}
	
	public int getCurrentPillar()
	{
		return currentPillar;
	}
	
	public void endProgram()
	{
		ledController.LEDOff(currentPillar-1);
	}
}